package ThreadDemo;

public class singal2 {
    static class singalton{
        private singalton(){}
        private static singalton instance=null;
        public static singalton getInstance(){
            if(instance==null){
                instance=new singalton();
            }
            return instance;
        }
    }
    //思考一下线程问题
    //如果多个线程同时进行，那么就会new出两个对象，就不是一个单例模式
    //pro版本:加锁
    static class singalton2{
        private singalton2(){}
        private static singalton2 instance=null;
        public static singalton2 getInstance(){
            //确保这的判断和修改的原子性
            synchronized(singalton2.class){
                if (instance == null) {
                    instance = new singalton2();
                }
            }
            return instance;
        }
    }
    //加入了锁必定会降低效率，所以需要提前判断一下instance的值
    static class singalton3{
        private singalton3(){}
        private static singalton3 instance=null;
        public static singalton3 getInstance() {
            //确保这的判断和修改的原子性
            if (instance==null) {
                synchronized (singalton3.class) {
                    if (instance == null) {
                        instance = new singalton3();
                    }
                }
            }
            return instance;
        }
    }
    //考虑一下这个instance，由于涉及多个读取操作，可能会被编译器进行优化，若是多个线程进行操作，可能会发生内存不可见问题

    static class singalton4{
        private singalton4(){}
        private volatile static singalton4 instance=null;
        public static singalton4 getInstance() {
            //确保这的判断和修改的原子性
            if (instance==null) {
                synchronized (singalton4.class) {
                    if (instance == null) {
                        instance = new singalton4();
                    }
                }
            }
            return instance;
        }
    }
}
